package com.pratik.test;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;

public class HelloWorldApp {
	
	private static Logger  logger = Logger.getLogger("HelloWorldApp.class");
	
	/**
	 * Executes the main business logic
	 * @param args Arguments
	 */
	public void execute(String[] args) {
		String name = processCommandLine(args);
		HelloWorld hWorld;
		if (name == null) {
			hWorld = new HelloWorld();
		} else {
			hWorld = new HelloWorld(name);
		}
		logger.info(hWorld.sayHello());
	}

	/**
	 * Processes command line to look for -name argument. 
	 * @param args The command line arguments 
	 * @return String containing value for name argument 
	 */
	public String processCommandLine(String[] args) {
		Options opt = new Options(); 
		opt.addOption("name", true, "User name");
		BasicParser parser = new BasicParser();
		try {
			CommandLine cl = parser.parse(opt, args);
			if (!cl.hasOption("name")) {
				logger.warn("Argument -name is missing, retrieving default value of variable name");
			} else {
				String name = cl.getOptionValue("name");
				logger.debug("String found for argument -name =>"+name);
				return name; 
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	
	/**
	 * Main
	 * @param args
	 */
	public static void main(String[] args) {
		HelloWorldApp appObj = new HelloWorldApp(); 
		appObj.execute(args);
	}

}
